#include "KeyViewWidget.h"
#include "ui_KeyViewWidget.h"
#include "Contact.h"

#include <QListWidgetItem>

using namespace kryptos::entities;

namespace kryptos { namespace ui {

KeyViewWidget::KeyViewWidget(QWidget *parent) :
    IKeyOperationWidget(parent),
    ui(new Ui::KeyViewWidget)
{
    ui->setupUi(this);

    ui->lwContacts->setProperty("active", false);

    connect(ui->lwGroups, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(groupSelected(QListWidgetItem*)));
}

KeyViewWidget::~KeyViewWidget()
{
    delete ui;
}

void KeyViewWidget::fillIdentitiesAndGroups(const GroupList& contacts)
{
    m_groupMap.clear();

    foreach(const Group& group, contacts)
    {
        std::string groupdisplay = group.name().c_str();
        if (group.type() == Group::VERNAM)
            groupdisplay += " - Vernam";

        ui->lwGroups->addItem(new QListWidgetItem(QString(groupdisplay.c_str())));

        foreach (const Contact& contact, group.members())
        {
            if (contact.keyInfo().isIdentity())
            {
                std::string display = contact.name() + " (" + contact.email() + ")";
                ui->lwKeys->addItem(new QListWidgetItem(QString(display.c_str())));
            }
        }

        m_groupMap[group.name().c_str()] = group;
    }
}

void KeyViewWidget::groupSelected(QListWidgetItem* item)
{
    QString groupname = item->text();

    groupname.remove(" - Vernam");

    ui->lwContacts->clear();

    foreach (const Contact& member, m_groupMap[groupname].members())
    {
        std::string display = member.name() + " (" + member.email() + ")";
        ui->lwContacts->addItem(new QListWidgetItem(QString(display.c_str())));
    }

    ui->lwContacts->setProperty("active", true);
    ui->lwContacts->style()->unpolish(ui->lwContacts);
    ui->lwContacts->style()->polish(ui->lwContacts);
}

QMap<QString, QString> KeyViewWidget::params()
{
    QMap<QString, QString> paramlist;
    return paramlist;
}

}}
